//
//  OneNewsItemView.m
//  BaoVn
//
//  Created by Le Anh Tai on 11/22/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "OneNewsItemView.h"

@implementation OneNewsItemView

- (instancetype)init
{
    if (self = [super init])
    {
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//        _webView = [[WKWebView alloc] init];
//        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
//#else
        _progressProxy = [[NJKWebViewProgress alloc] init]; // instance variable
        _progressProxy.webViewProxyDelegate = self;
        _progressProxy.progressDelegate = self;
        
        [self newWebView];
//#endif
        
        _progressContainer = [[UIView alloc] init];
        [_progressContainer setBackgroundColor:[UIColor whiteColor]];
        [self addSubview:_progressContainer];
        
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
        [_progressContainer addSubview:_progressView];
        
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.decelerationRate = UIScrollViewDecelerationRateFast;
    }
    
    return self;
}

- (void)newWebView
{
    if (_webView)
    {
        [_webView stopLoading];
        _webView.delegate = nil;
        [_webView removeFromSuperview];
        _webView = nil;
    }
    
    _webView = [[UIWebView alloc] init];
    _webView.delegate = _progressProxy;
    [_webView setScalesPageToFit:YES];
    
    [self addSubview:_webView];
}

- (void)loadUrl:(NSString *)url
{
    if (url == nil)
    {
        return;
    }
    
    [self setProgress:0 animated:NO];

    [self newWebView];
    [self bringSubviewToFront:_progressContainer];
    
    self.frame = self.frame;
    
    _url = url;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
}

- (void)setProgress:(float)process animated:(BOOL)animated
{
    [_progressView setProgress:process animated:animated];
    
    _progressContainer.hidden = (process == 0);
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    _progressContainer.frame = CGRectMake(0, 0, self.width, 1.5f);

    _progressContainer.layer.masksToBounds = NO;
    _progressContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    _progressContainer.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
    _progressContainer.layer.shadowOpacity = 0.8f;

    _progressView.frame = CGRectMake(0, 0, _progressContainer.width, _progressContainer.height);
    
    _webView.frame = RECT(0, 0, self.width, self.height);
    self.contentSize = SIZE(self.width + 1, self.height);
}

- (void)dealloc
{
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
//#endif
}

#pragma mark -

//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//
//
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"estimatedProgress"] && object == _webView) {
//
//        [_progressView setProgress:_webView.estimatedProgress animated:YES];
//        
//        //hide progressView when done
//        if (_webView.estimatedProgress == 1)
//        {
//            [_progressView performSelector:@selector(setProgress:) withObject:[NSNumber numberWithFloat:0] afterDelay:0.25];
//        }
//    }
//    else {
//        // Make sure to call the superclass's implementation in the else block in case it is also implementing KVO
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
//}
//#endif

#pragma mark -
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [self setProgress:progress animated:YES];
    
    //hide progressView when done
    if (progress == 1)
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [NSThread sleepForTimeInterval:0.4];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setProgress:0 animated:NO];
            });
        });
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([_delegateWebView respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)])
    {
        return [_delegateWebView webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if ([_delegateWebView respondsToSelector:@selector(webViewDidStartLoad:)])
    {
        [_delegateWebView webViewDidStartLoad:webView];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([_delegateWebView respondsToSelector:@selector(webViewDidFinishLoad:)])
    {
        [_delegateWebView webViewDidFinishLoad:webView];
    }
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if ([_delegateWebView respondsToSelector:@selector(webView:didFailLoadWithError:)])
    {
        [_delegateWebView webView:webView didFailLoadWithError:error];
    }
    
//    //
//    if (_alertView)
//    {
//        return;
//    }
//    
//    NSString *errorMsg;
//    
//    if ([error code] == -1202)
//    {
//        errorMsg = [NSString stringWithFormat:@"Cannot verify the identity of \"%@\". Would you like to continue anyway?", _url];
//        
//        _alertView = [[UIAlertView alloc] initWithTitle:@"Cannot Verify Server Identity"
//                                                message:errorMsg
//                                               delegate:self
//                                      cancelButtonTitle:@"Cancel"
//                                      otherButtonTitles:@"Continue", nil];
//    }
//    else
//    {
//        errorMsg = error.localizedDescription;
//        
//        _alertView = [[UIAlertView alloc] initWithTitle:@"Error"
//                                                message:errorMsg
//                                               delegate:self
//                                      cancelButtonTitle:@"Dismiss"
//                                      otherButtonTitles:nil];
//    }
//    
//    [_alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    _alertView = nil;
    
    [_progressView setProgress:0];
    
    //Cancel
    if (buttonIndex == 0)
    {
        
    }
    //Continue
    else if (buttonIndex == 1)
    {
        //bypass SSL
    }
    
}

- (NSString *)getCurrentWebViewTitle
{
    if (_webView == nil)
    {
        return @"";
    }
    
    return [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
@end
